package com.supor.aiot.common.entity;

/**
 * A generic class that holds a result success w/ data or an error exception.
 */
public class Result<T> {
    protected T data;
    protected Exception error;
    protected String errorMsg;

    // hide the private constructor to limit subclass types (Success, Error)
    private Result() {
    }

    public T getData() {
        return data;
    }

    public Exception getError() {
        return error;
    }

    @Override
    public String toString() {
        if (this instanceof Result.Success) {
            Result.Success success = (Result.Success) this;
            if (success.getData() != null) {
                return "Success[data=" + success.getData().toString() + "]";
            }
        } else if (this instanceof Result.Error) {
            Result.Error error = (Result.Error) this;
            if (error.getError() != null) {
                return "Error[exception=" + error.getError().toString() + "]";
            }
        }
        return "";
    }

    // Success sub-class
    public final static class Success<T> extends Result<T> {

        public Success(T data) {
            this.data = data;
        }

        public T getData() {
            return this.data;
        }
    }

    // Error sub-class
    public final static class Error extends Result {

        public Error(Exception error) {
            this.error = error;
        }

        public Error(String errorMsg) {
            this.errorMsg = errorMsg;
        }

        public Exception getError() {
            return this.error;
        }

        public String getErrorMsg() {
            if (error != null) {
                return error.getMessage();
            }
            return this.errorMsg;
        }
    }
}